import { fetchLogin } from '../../../api/login';
import { Dispatch } from 'redux'
import { ILoginParams } from '../types';
import { NavigateFunction } from 'react-router-dom'
import * as types from './constans';

export const actionSaveToken = (token: string) => ({
  type: types.SAVE_TOKEN,
  payload: token
})
export const actionSaveProfile = (profile: any) => ({
  type: types.SAVE_TOKEN,
  payload: profile
})

export const actionFecthLogin = (params: ILoginParams, redirect?: NavigateFunction) => {

  return (dispath: Dispatch) => {
    fetchLogin(params).then((res: any) => {
      if (res.message === 'OK' && res.data) {
        window.localStorage.setItem('token', res.data.token)
        dispath(actionSaveProfile(res.data));
        redirect && redirect('/layout')
      }
    });
  }

}